/**
 *
 *
 *
 *
 *
 */

package org.sxp.modules.oss.cloud;


import org.apache.commons.io.IOUtils;
import org.sxp.common.exception.XPException;

import javax.annotation.processing.FilerException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 腾讯云存储
 *
 *
 */
public class LocalFileStorageService extends CloudStorageService {

    public LocalFileStorageService(CloudStorageConfig config){
        this.config = config;

        //初始化
        init();
    }

    private void init(){

    }

    @Override
    public String upload(byte[] data, String path) {
        FileOutputStream out = null;
        File file = new File(path);
        try {
            if(file.isDirectory()){
                throw new FilerException("path参数不是有效的文件路径!");
            }else if(!file.exists()){
                file.getParentFile().mkdirs();
            }

            out = new FileOutputStream(file);
            out.write(data);
            out.flush();
        }catch (Exception e){
            throw new XPException("上传文件失败", e);
        }finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {

                }
            }
        }

        return file.getPath();
    }

    @Override
    public String upload(InputStream inputStream, String path) {
    	try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new XPException("上传文件失败", e);
        }
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getFilePath(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getQcloudPrefix(), suffix));
    }
}
